
package com.qianfeng.libra.cowshop.app.activities;

import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.wechat.friends.Wechat;
import android.widget.*;
import com.qianfeng.libra.cowshop.app.R;
import com.qianfeng.libra.cowshop.app.configuration.Constants;
import com.qianfeng.libra.cowshop.app.db.DBHelper;
import com.qianfeng.libra.cowshop.app.models.SaleProduct;
import com.qianfeng.libra.cowshop.app.models.TopicProduct;
import com.qianfeng.libra.cowshop.app.tasks.DownloadDataTask;
import com.qianfeng.libra.cowshop.app.tasks.TaskProcessor;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

public class ProductDetailActivity extends FragmentActivity implements TaskProcessor, View.OnClickListener, Runnable {
    private SaleProduct saleProduct;
    private List<String> imgUrlList;
    private RadioGroup radioGroup;

    private String detailUrl = "http://s.it168.com/AppService/QHMProduct.asmx/GetQHMSaleProductByID?QHMSaleProductSN=";
    private String QHMSaleProductSN = null;
    private PopupWindow popupWindow;
    private LinearLayout cover;
    private PopupWindow popupGoCart;

    private SQLiteDatabase database;
    private DBHelper dbHelper;
    private TopicProduct topicProduct;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_product_detail);
        Intent intent = getIntent();

        topicProduct = (TopicProduct) intent.getSerializableExtra("TopicProduct");
        QHMSaleProductSN = topicProduct.getQHMSaleProductSN();

        cover = (LinearLayout) findViewById(R.id.layout_cover);
        cover.setOnClickListener(this);
        saleProduct = new SaleProduct();
        imgUrlList = new LinkedList<String>();
        ImageView imageShare = (ImageView) findViewById(R.id.img_share);
        imageShare.setOnClickListener(this);
        radioGroup = (RadioGroup) findViewById(R.id.product_poster_switch);

        dbHelper = new DBHelper(this);
        radioGroup = (RadioGroup) findViewById(R.id.product_poster_switch);

        DownloadDataTask downloadDataTask = new DownloadDataTask(this);
        downloadDataTask.execute(detailUrl + QHMSaleProductSN);

    }


    public void btnAddCart(View v) {

        if (saleProduct != null) {
            // 用于创建 AlertDialog的

            LayoutInflater inflater = LayoutInflater.from(this);
            View view = inflater.inflate(R.layout.cart_info, null);
            popupWindow = new PopupWindow(view, ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.WRAP_CONTENT);
            popupWindow.showAtLocation(findViewById(R.id.layout_detail), Gravity.BOTTOM, 0, 0);
            cover.setVisibility(View.VISIBLE);
            TextView txtPrice = (TextView) view.findViewById(R.id.txt_product_price);
            txtPrice.setText("￥" + String.valueOf((float) saleProduct.getPrice()));

            TextView txtStock = (TextView) view.findViewById(R.id.txt_stock);
            txtStock.setText("库存：" + String.valueOf(saleProduct.getStock()));

            TextView txtLimit = (TextView) view.findViewById(R.id.txt_limit_num);
            txtLimit.setText("(限购" + String.valueOf(saleProduct.getLimitSaleNum()) + "件)");

            final TextView txtBuyNum = (TextView) view.findViewById(R.id.txt_buy_num);

            TextView btnCancel = (TextView) view.findViewById(R.id.btn_cancel);
            btnCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                    cover.setVisibility(View.GONE);
                }
            });

            TextView btnGoCart = (TextView) view.findViewById(R.id.btn_go_cart);
            btnGoCart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SharedPreferences sharedPreferences = getSharedPreferences(Constants.SP_APP_DATA, MODE_PRIVATE);
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putBoolean("isCartEmpty", false);
                    edit.commit();
                    boolean isLogin = sharedPreferences.getBoolean("isLogin", false);
                    int i = Integer.parseInt(txtBuyNum.getText().toString());
                    if (isLogin) {
                        // TODO 发送网络请求，提交商品信息，获取购物车信息
                    } else {
                        StorageDB(i);
                    }
                    popupWindow.dismiss();
                    showCartGo();
                }
            });

            ImageView imgAdd = (ImageView) view.findViewById(R.id.btn_add);
            imgAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int oriNum = Integer.parseInt(txtBuyNum.getText().toString());
                    int i = oriNum + 1;
                    if (i > saleProduct.getLimitSaleNum()) {
                        Toast.makeText(ProductDetailActivity.this, "超过限购数量！", Toast.LENGTH_SHORT).show();
                    } else {
                        txtBuyNum.setText(String.valueOf(i));
                    }
                }
            });

            ImageView imgSub = (ImageView) view.findViewById(R.id.btn_sub);
            imgSub.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int oriNum = Integer.parseInt(txtBuyNum.getText().toString());
                    int i = oriNum - 1;
                    if (i < 1) {
                        Toast.makeText(ProductDetailActivity.this, "数目不能小于1！", Toast.LENGTH_SHORT).show();
                    } else {
                        txtBuyNum.setText(String.valueOf(i));
                    }
                }
            });

        } else {
            Toast.makeText(this, "数据加载中", Toast.LENGTH_SHORT).show();
        }
    }

    private void StorageDB(int buyNum) {
        database = dbHelper.getWritableDatabase();
        database.beginTransaction();
        try {
            ContentValues values = new ContentValues();
            values.put("productimg", saleProduct.getSmallImageSN());
            values.put("productsn", topicProduct.getProductSN());
            values.put("saleproductid", topicProduct.getQHMSaleProductSN());
            values.put("shoppingnum", buyNum);
            values.put("EBPrice", topicProduct.getEbbPrice());
            values.put("Price", topicProduct.getPrice());
            values.put("ShortPrice", topicProduct.getShortPrice());
            values.put("stock", saleProduct.getStock());
            values.put("allowbuycount", saleProduct.getLimitSaleNum());
            database.insert("carts", null, values);
            database.setTransactionSuccessful();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            database.endTransaction();
        }
        database.close();
    }

    private void showCartGo() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.cart_go_to, null);
        popupGoCart = new PopupWindow(view, ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.WRAP_CONTENT);
        popupGoCart.showAtLocation(findViewById(R.id.layout_detail), Gravity.BOTTOM, 0, 0);
        Thread thread = new Thread(this);
        thread.start();
        LinearLayout layoutGoCart = (LinearLayout) view.findViewById(R.id.layout_go_cart);
        layoutGoCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupGoCart.dismiss();
                cover.setVisibility(View.GONE);
                Intent intent = new Intent(ProductDetailActivity.this, CartActivity.class);
                startActivity(intent);
            }
        });

    }

    public void btnBack(View v) {
        finish();
    }

    @Override
    public void processResult(JSONObject result) {
        try {
            JSONObject info = result.getJSONObject("info");
            JSONObject saleProductForOne = info.getJSONObject("SaleProductForOne");
            saleProduct.parseJSON(saleProductForOne);
            JSONArray imageList = info.getJSONArray("ImageList");
            for (int i = 0; i < imageList.length(); i++) {
                JSONObject jsonObject = imageList.getJSONObject(i);
                String imageSN = jsonObject.getString("ImageSN");
                imgUrlList.add(imageSN);
            }
            init(saleProduct);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void init(SaleProduct saleProduct) {
        if (saleProduct != null) {
            TextView txtShortPrice = (TextView) findViewById(R.id.txt_short_price);
            txtShortPrice.setText(String.valueOf(saleProduct.getShortPrice()));
            TextView txtTitle = (TextView) findViewById(R.id.txt_title);
            txtTitle.setText(saleProduct.getTitle());
            TextView txtPrice = (TextView) findViewById(R.id.txt_price);
            txtPrice.setText("￥" + String.valueOf(saleProduct.getPrice()));
            TextView txtOriPrice = (TextView) findViewById(R.id.txt_ori_price);
            txtOriPrice.setText("￥" + String.valueOf(saleProduct.getEbbPrice()));
            TextView txtShortSmall = (TextView) findViewById(R.id.txt_short_small);
            txtShortSmall.setText("￥" + String.valueOf(saleProduct.getShortPrice()));
            WebView myWebView = (WebView) findViewById(R.id.web_detail);
            WebSettings webSettings = myWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            myWebView.setHorizontalScrollBarEnabled(false);
            webSettings.setSupportZoom(true);
            webSettings.setBuiltInZoomControls(false);
            myWebView.setHorizontalScrollbarOverlay(true);
            myWebView.loadUrl(saleProduct.getProductHtml());

        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.layout_cover:
                popupWindow.dismiss();
                if (popupGoCart != null) {
                    popupGoCart.dismiss();
                }
                cover.setVisibility(View.GONE);
                break;
            case R.id.img_share:
                ShareSDK.initSDK(this);
                // 一键分享的代码
        /*Platform wei=new Wechat(this)
        Platform weibo = ShareSDK.getPlatform(.NAME);*/
                OnekeyShare oks = new OnekeyShare();
                // 分享时Notification的图标和文字
                oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
                // 分享的文字内容
                oks.setText("Android第三方登录分享功能开发测试用例 请忽略");
                // 设置分享的图片
                oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/05/21/oESpJ78_533x800.jpg");
                // 启动分享GUI
                oks.show(this);
                break;
        }
    }

    @Override
    public void run() {
        try {
            Thread.sleep(3000);

            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                if (popupGoCart.isShowing()) {
                    popupGoCart.dismiss();
                    cover.setVisibility(View.GONE);
                }
            }
            super.handleMessage(msg);
        }
    };

}